"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 扩展查询之在函数、存储过程、匿名块中进行只读查询
Create At   : 2023/07/12
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.在主机创建表，创建函数，创建存储过程
    3.扩展查询之在函数、存储过程、匿名块中进行只读查询
    4.查看日志打印
    5.环境清理，恢复参数
Expect      :
    1.修改成功
    2.创建成功
    3.执行成功
    4.日志记录libpqsw报文信息，匿名块转发给主机执行
    5.环境清理成功，恢复参数成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != PrimarySh.get_node_num(), '非1主2备环境不执行')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_root = Node('Standby2Root')
        self.standby_node = Node('Standby2DbUser')
        self.standby_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.common = Common('Standby2DbUser')
        self.common_root = Common('Standby2Root')
        self.table_name = 't_multi_node_write_0039'
        self.func_name = 'func_multi_node_write_0039'
        self.proc_name = 'proc_multi_node_write_0039'
        self.java_file = "Opengauss_SharedStorage_MultiNodeWrite_Case0039.java"
        self.target_path = os.path.join(macro.DB_MY_PATH,
                                        'JDBC_multi_node_write_0039')
        self.properties = os.path.join(
            self.target_path, 'JDBC_MultiNodeWrite_Case0039.properties')
        self.new_jdbc_path = os.path.join(self.target_path, 'postgresql.jar')
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_multi_node_write0039')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir} {self.target_path};echo $?;"
        self.logger.info(shell_cmd)
        shell_res = self.common.get_sh_result(self.standby_root, shell_cmd)
        self.assertEqual('0', shell_res.splitlines()[-1].strip(),
                         '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute} = on')
        self.assertTrue(result, f'执行失败:{step1}')
        stop_res = self.standby_sh.exec_cm_ctl('stop')
        self.logger.info(stop_res)
        self.assertIn(self.constant.cm_stop_success_msg, stop_res,
                      f'stop集群失败:{step1}')
        start_res = self.standby_sh.exec_cm_ctl('start')
        self.logger.info(start_res)
        self.assertIn(self.constant.cm_start_success_msg, start_res,
                      f'start集群失败:{step1}')
        time.sleep(5)
        status = self.standby_sh.exec_cm_ctl('query', '-Cv')
        self.logger.info(status)
        self.assertTrue("cluster_state   : Normal" in status, '集群状态异常')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement} = all')
        self.assertTrue(result, f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory} = '{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')

        step2 = "-----step2:在主机创建表，创建函数，创建存储过程;expect:创建成功-----"
        self.logger.info(step2)
        sql_cmd = f'''drop table if exists {self.table_name};
            create table {self.table_name}(id int);
            select pg_sleep(1);
            insert into {self.table_name} values(generate_series(1,10));'''
        sql_msg = PrimarySh.execut_db_sql(
            sql_cmd, f"-U {self.standby_node.db_user} "
                     f"-W '{self.standby_node.db_password}'")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(2)
        sql_cmd = f'''create or replace function {self.func_name}() 
            returns int as 
            \\$\\$ 
            select * from {self.table_name};
            \\$\\$
            language sql;'''
        sql_msg = PrimarySh.execut_db_sql(
            sql_cmd, f"-U {self.standby_node.db_user} "
                     f"-W '{self.standby_node.db_password}'")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step2}')
        sql_cmd = f'''create or replace procedure {self.proc_name}() is 
            begin 
                execute immediate 'select * from {self.table_name};';
            end;'''
        sql_msg = PrimarySh.execut_db_sql(
            sql_cmd, f"-U {self.standby_node.db_user} "
                     f"-W '{self.standby_node.db_password}'")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:扩展查询之在函数、存储过程、匿名块中进行只读查询;" \
                "expect:执行成功-----"
        self.logger.info(step3)
        self.logger.info('-----复制java脚本至指定的主机路径-----')
        self.common_root.scp_file(
            self.standby_root, self.java_file, self.target_path)
        self.logger.info('-----复制jdbc jar包至指定的主机路径-----')
        self.standby_root.scp_put(macro.JDBC_PATH, self.new_jdbc_path)
        cmd = f'ls {self.target_path}'
        self.logger.info(cmd)
        res = self.standby_root.sh(cmd).result()
        self.logger.info(res)
        self.assertIn(self.java_file, res, f'复制java脚本失败:{step3}')
        self.assertIn('postgresql.jar', res, f'复制jar包失败:{step3}')
        self.logger.info('-----创建配置文件-----')
        touch_res = self.common_root.get_sh_result(
            self.standby_root, f"touch {self.properties}")
        self.assertEquals('', touch_res, '创建配置文件失败')
        config = f'echo "password=' \
                 f'{self.standby_node.db_password}"> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "port={self.standby_node.db_port}">> ' \
                 f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "hostname={self.standby_node.db_host}">> ' \
                 f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "user={self.standby_node.db_user}">> ' \
                 f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "dbname={self.standby_node.db_name}">> ' \
                 f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "tbname={self.table_name}">> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "funcname={self.func_name}">> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "procname={self.proc_name}">> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        shell_cmd = f'cat {self.properties}'
        self.logger.info(shell_cmd)
        shell_msg = self.common_root.get_sh_result(self.standby_root, shell_cmd)
        self.assertTrue("password=" in shell_msg and "port=" in shell_msg
                        and "hostname=" in shell_msg and "user=" in shell_msg
                        and "dbname=" in shell_msg and "tbname=" in shell_msg
                        and "funcname=" in shell_msg
                        and "procname=" in shell_msg, '创建配置文件失败')
        self.logger.info('-----编译java文件-----')
        compile_cmd = f"cd {self.target_path};" \
                      f"javac -encoding utf-8 -cp {self.new_jdbc_path} {self.java_file}"
        self.logger.info(compile_cmd)
        compile_msg = self.common_root.get_sh_result(self.standby_root,
                                                     compile_cmd)
        self.assertNotIn('ERROR', compile_msg, f'编译失败:{step3}')
        self.logger.info('-----运行java预编译代码-----')
        java_cmd = f"cd {self.target_path};" \
                   f"java -cp {self.new_jdbc_path}:{self.target_path} " \
                   f"{self.java_file[:-5]} -F {self.properties}"
        self.logger.info(java_cmd)
        java_msg = self.common_root.get_sh_result(self.standby_root, java_cmd)
        self.assertIn(f'The CallableStatment {self.func_name} returns:1',
                      java_msg, '运行失败')
        self.assertIn(f'The CallableStatment {self.proc_name} returns:null',
                      java_msg, '运行失败')
        self.assertNotIn('ERROR', java_msg, '编译失败')
        time.sleep(5)

        step4 = "-----step4:查看日志打印;expect:日志记录libpqsw报文信息，匿名块转发给主机-----"
        self.logger.info(step4)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[0])
        self.logger.info(logfile)
        shell_cmd = f"grep {self.standby_node.db_name} {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertIn(f'LOG:  execute <unnamed>: select * from '
                      f'{self.func_name}', shell_msg, f'执行失败:{step4}')
        self.assertIn(f"[TRACE] P: portal=, stmt=select * from "
                      f"{self.proc_name}", shell_msg, f'执行失败:{step4}')
        self.assertIn(f'we find pbe new select cmdtag:SELECT, sql:select * '
                      f'from {self.proc_name}', shell_msg, f'执行失败:{step4}')
        self.assertIn(f"find pbe new transfer cmdtag:ANONYMOUS BLOCK EXECUTE, "
                      f"sql:declare begin execute immediate 'select * from "
                      f"{self.table_name};';end;", shell_msg,
                      f'执行失败:{step4}')

    def tearDown(self):
        step4 = "-----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step4)
        drop_cmd = f"drop table if exists {self.table_name};" \
                   f"drop function {self.func_name};" \
                   f"drop procedure {self.proc_name};"
        drop_msg = PrimarySh.execut_db_sql(
            drop_cmd, f"-U {self.standby_node.db_user} "
                      f"-W '{self.standby_node.db_password}'")
        self.logger.info(drop_msg)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        shell_cmd = f"rm -rf {self.target_path} {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_root, shell_cmd)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_msg, f'执行失败:{step4}')
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG,
                      drop_msg, f'执行失败:{step4}')
        self.assertIn(self.constant.DROP_PROCEDURE_SUCCESS_MSG,
                      drop_msg, f'执行失败:{step4}')
        self.assertTrue(restart_res, f'执行失败:{step4}')
        self.assertTrue(result1 and result2 and result3, f'执行失败:{step4}')
        self.assertEquals('', shell_msg, '删除目录失败')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
